{% extends 'base.html' %}
{% load static %}

{% block title %}{{ worldcup.name }} - 冠军赛对战图{% endblock %}

{% block extra_css %}
<style>
    .worldcup-championship {
        max-width: 1400px;
        margin: 0 auto;
        padding: 15px;
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
        min-height: 100vh;
        color: #ffffff;
    }

    .page-header {
        text-align: center;
        margin-bottom: 15px;
        padding: 15px 0;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 12px;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .page-title {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 8px;
        background: linear-gradient(45deg, #ffd700, #ffed4e);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .page-subtitle {
        font-size: 1rem;
        color: #b0b0b0;
        margin-bottom: 15px;
    }

    .tournament-legend {
        display: flex;
        justify-content: center;
        gap: 12px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 6px 12px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 15px;
        font-size: 0.8rem;
    }

    .legend-color {
        width: 12px;
        height: 12px;
        border-radius: 50%;
    }

    .legend-pending { background-color: #6c757d; }
    .legend-progress { background-color: #ffc107; }
    .legend-completed { background-color: #28a745; }

    /* 世界杯状态样式 */
    .status-preparing {
        background-color: #6c757d;
        color: white;
    }

    .status-regular_season {
        background-color: #17a2b8;
        color: white;
    }

    .status-regular_finished {
        background-color: #fd7e14;
        color: white;
    }

    .status-championship {
        background-color: #ffc107;
        color: #000;
    }

    .status-finished {
        background-color: #28a745;
        color: white;
    }

    .tournament-bracket {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        gap: 15px;
        margin-bottom: 20px;
        padding: 10px;
    }

    .bracket-side {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .bracket-center {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 20px;
        min-height: 500px;
    }

    .bracket-round {
        display: flex;
        flex-direction: column;
        gap: 15px;
        min-width: 180px;
    }

    .bracket-round.left-16 {
        justify-content: space-around;
    }

    .bracket-round.right-16 {
        justify-content: space-around;
    }

    .bracket-round.quarter-left,
    .bracket-round.quarter-right {
        justify-content: space-around;
    }

    .bracket-round.semi-left,
    .bracket-round.semi-right {
        justify-content: center;
    }

    .bracket-round.final {
        justify-content: center;
    }

    .bracket-round.champion {
        justify-content: center;
        align-items: center;
    }

    .round-title {
        text-align: center;
        font-size: 1.2rem;
        font-weight: bold;
        padding: 10px;
        background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
        border-radius: 8px;
        margin-bottom: 15px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
    }

    .match-card {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        padding: 15px;
        margin-bottom: 10px;
        border: 2px solid transparent;
        transition: all 0.3s ease;
        backdrop-filter: blur(10px);
    }

    .match-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
    }

    .match-card.completed {
        border-color: #28a745;
        background: rgba(40, 167, 69, 0.1);
    }

    .match-card.in-progress {
        border-color: #ffc107;
        background: rgba(255, 193, 7, 0.1);
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); }
        70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
        100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
    }

    .match-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding-bottom: 8px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    .match-stage {
        font-weight: bold;
        color: #ffd700;
        font-size: 0.9rem;
    }

    .match-status {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.7rem;
        font-weight: bold;
    }

    .status-pending {
        background-color: #6c757d;
        color: white;
    }

    .status-in_progress {
        background-color: #ffc107;
        color: #000;
    }

    .status-completed {
        background-color: #28a745;
        color: white;
    }

    .status-awarded {
        background: linear-gradient(45deg, #ffd700, #ffed4e);
        color: #000;
        font-weight: bold;
        box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
        animation: award-glow 2s ease-in-out infinite alternate;
    }

    @keyframes award-glow {
        from { box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3); }
        to { box-shadow: 0 2px 12px rgba(255, 215, 0, 0.5); }
    }

    .match-players {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .player-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 10px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 6px;
        transition: all 0.3s ease;
    }

    .player-row.winner {
        background: rgba(40, 167, 69, 0.2);
        border: 1px solid #28a745;
    }

    .player-row.loser {
        background: rgba(108, 117, 125, 0.2);
        opacity: 0.7;
    }

    /* 待进行比赛的红蓝队伍颜色 */
    .player-row.red-team {
        background: rgba(220, 53, 69, 0.15);
        border: 1px solid rgba(220, 53, 69, 0.3);
    }

    .player-row.blue-team {
        background: rgba(13, 110, 253, 0.15);
        border: 1px solid rgba(13, 110, 253, 0.3);
    }

    .player-name {
        font-weight: 500;
        flex: 1;
        font-size: 0.9rem;
    }

    .player-name.winner {
        color: #28a745;
        font-weight: bold;
    }

    .player-name.red-team {
        color: #dc3545;
        font-weight: 500;
    }

    .player-name.blue-team {
        color: #0d6efd;
        font-weight: 500;
    }

    .player-score {
        font-weight: bold;
        font-size: 1rem;
        color: #ffd700;
        margin-left: 8px;
    }

    .vs-divider {
        text-align: center;
        font-weight: bold;
        color: #ffd700;
        margin: 3px 0;
        font-size: 0.8rem;
    }



    .champion-card {
        text-align: center;
        padding: 20px;
        background: linear-gradient(45deg, #ffd700, #ffed4e);
        color: #000;
        border-radius: 12px;
        box-shadow: 0 6px 20px rgba(255, 215, 0, 0.3);
        animation: glow 2s ease-in-out infinite alternate;
    }

    @keyframes glow {
        from { box-shadow: 0 6px 20px rgba(255, 215, 0, 0.3); }
        to { box-shadow: 0 6px 25px rgba(255, 215, 0, 0.5); }
    }

    .champion-title {
        font-size: 1.2rem;
        font-weight: bold;
        margin-bottom: 8px;
    }

    .champion-name {
        font-size: 1.5rem;
        font-weight: bold;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #b0b0b0;
    }

    .empty-icon {
        font-size: 4rem;
        margin-bottom: 20px;
        opacity: 0.5;
    }

    .action-buttons {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 40px;
        flex-wrap: wrap;
    }

    .btn-action {
        padding: 12px 24px;
        border-radius: 25px;
        text-decoration: none;
        font-weight: bold;
        transition: all 0.3s ease;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-secondary {
        background: rgba(108, 117, 125, 0.2);
        color: #ffffff;
        border: 1px solid #6c757d;
    }

    .btn-secondary:hover {
        background: #6c757d;
        transform: translateY(-2px);
    }

    .btn-success {
        background: rgba(40, 167, 69, 0.2);
        color: #ffffff;
        border: 1px solid #28a745;
    }

    .btn-success:hover {
        background: #28a745;
        transform: translateY(-2px);
    }

    @media (max-width: 1200px) {
        .tournament-bracket {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    /* 冠军赛排行榜样式 */
    .championship-rankings .table-header,
    .championship-rankings .ranking-row {
        display: grid;
        grid-template-columns: 80px 1fr 120px 120px 150px 120px;
        gap: 15px;
        padding: 15px 20px;
    }

    @media (max-width: 1200px) {
        .tournament-bracket {
            grid-template-columns: repeat(2, 1fr);
        }

        .championship-rankings .table-header,
        .championship-rankings .ranking-row {
            grid-template-columns: 60px 1fr 100px 100px 120px 100px;
            gap: 10px;
            padding: 12px 15px;
            font-size: 0.9rem;
        }
    }

    /* 页签导航样式 */
    .tab-navigation {
        margin-bottom: 20px;
    }

    .tab-buttons {
        display: flex;
        justify-content: center;
        gap: 10px;
        margin-bottom: 20px;
        padding: 0 20px;
    }

    .tab-button {
        padding: 12px 24px;
        border: 2px solid rgba(255, 255, 255, 0.2);
        background: rgba(255, 255, 255, 0.1);
        color: #ffffff;
        border-radius: 25px;
        font-weight: bold;
        font-size: 1rem;
        cursor: pointer;
        transition: all 0.3s ease;
        backdrop-filter: blur(10px);
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .tab-button:hover {
        background: rgba(255, 255, 255, 0.2);
        border-color: rgba(255, 255, 255, 0.4);
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    }

    .tab-button.active {
        background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
        border-color: #667eea;
        color: #ffffff;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }

    .tab-button.active:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }

    /* 页签内容样式 */
    .tab-content {
        display: none;
        animation: fadeIn 0.3s ease-in-out;
    }

    .tab-content.active {
        display: block;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    @media (max-width: 768px) {
        .tournament-bracket {
            grid-template-columns: 1fr;
        }

        .page-title {
            font-size: 2rem;
        }

        .worldcup-championship {
            padding: 15px;
        }

        .tab-buttons {
            flex-direction: column;
            align-items: center;
            gap: 8px;
            padding: 0 10px;
        }

        .tab-button {
            width: 100%;
            max-width: 300px;
            justify-content: center;
            padding: 10px 20px;
            font-size: 0.9rem;
        }

        .championship-rankings .table-header,
        .championship-rankings .ranking-row {
            grid-template-columns: 50px 1fr 80px 80px;
            gap: 8px;
            padding: 10px 12px;
            font-size: 0.8rem;
        }

        .championship-rankings .table-header div:nth-child(5),
        .championship-rankings .table-header div:nth-child(6),
        .championship-rankings .ranking-row div:nth-child(5),
        .championship-rankings .ranking-row div:nth-child(6) {
            display: none;
        }

        .championship-rankings .rankings-header h2 {
            font-size: 1.4rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="worldcup-championship">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'battles:worldcup_list' %}">世界杯列表</a></li>
            <li class="breadcrumb-item"><a href="{% url 'battles:worldcup_detail' worldcup.id %}">{{ worldcup.name }}</a></li>
            <li class="breadcrumb-item active" aria-current="page">冠军赛对战图</li>
        </ol>
    </nav>

    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">🏆 {{ worldcup.name }} - 冠军赛对战图</h1>
        <p class="page-subtitle">16强晋级决赛的完整对战路线</p>

        <!-- 世界杯状态 -->
        <div class="worldcup-status-info" style="margin: 15px 0; padding: 10px 20px; background: rgba(255, 255, 255, 0.1); border-radius: 8px; border: 1px solid rgba(255, 255, 255, 0.2);">
            <span class="worldcup-status status-{{ worldcup.status }}" style="display: inline-block; padding: 4px 12px; border-radius: 15px; font-size: 0.9rem; font-weight: bold;">
                {% if worldcup.status == 'championship' %}
                    🏆 冠军赛进行中
                {% elif worldcup.status == 'finished' %}
                    {% if worldcup.championship_started_at %}
                        🏆 冠军赛已结束
                    {% else %}
                        ✅ 已结束
                    {% endif %}
                {% else %}
                    🔧 {{ worldcup.get_status_display }}
                {% endif %}
            </span>
            {% if worldcup.status == 'finished' and worldcup.finished_at %}
                <span style="margin-left: 15px; color: #b0b0b0; font-size: 0.85rem;">
                    结束时间：{{ worldcup.finished_at|date:"Y-m-d H:i" }}
                </span>
            {% endif %}
        </div>

        <!-- 图例 -->
        <div class="tournament-legend">
            <div class="legend-item">
                <div class="legend-color legend-pending"></div>
                <span>待进行</span>
            </div>
            <div class="legend-item">
                <div class="legend-color legend-progress"></div>
                <span>进行中</span>
            </div>
            <div class="legend-item">
                <div class="legend-color legend-completed"></div>
                <span>已完成</span>
            </div>
        </div>
    </div>

    <!-- 页签导航 -->
    {% if matches_by_stage.round_16 or matches_by_stage.quarter_final or matches_by_stage.semi_final or matches_by_stage.final %}
    <div class="tab-navigation">
        <div class="tab-buttons">
            <button class="tab-button active" onclick="switchTab('bracket')" id="bracket-tab">
                🏆 对战图
            </button>
            {% if worldcup.status == 'finished' and championship_rankings %}
            <button class="tab-button" onclick="switchTab('rankings')" id="rankings-tab">
                🥇 总排行榜
            </button>
            {% endif %}
        </div>
    </div>

    <!-- 对战图内容 -->
    <div id="bracket-content" class="tab-content active">
        <div class="tournament-bracket">
            <!-- 左侧16强 -->
            <div class="bracket-side">
                <div class="bracket-round left-16">
                    <div class="round-title">16强 (左)</div>
                    {% for match in matches_by_stage.round_16 %}
                        {% if forloop.counter <= 4 %}
                        <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                            <div class="match-header">
                                <span class="match-stage">R16-{{ forloop.counter }}</span>
                                <span class="match-status status-{% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                                    {% if match.is_completed %}已完成
                                    {% elif match.battle and match.battle.status == 'running' %}进行中
                                    {% else %}待进行
                                    {% endif %}
                                </span>
                            </div>
                            <div class="match-players">
                                <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                                    <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                        {{ match.participant1.user.username|default:"待定" }}
                                    </span>
                                    {% if match.is_completed %}
                                    <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                                    {% endif %}
                                </div>
                                <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                                <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                                    <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                        {{ match.participant2.user.username|default:"待定" }}
                                    </span>
                                    {% if match.is_completed %}
                                    <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>

        <!-- 左侧8强 -->
        <div class="bracket-side">
            <div class="bracket-round quarter-left">
                <div class="round-title">🎉 8强 (左)</div>
                {% for match in matches_by_stage.quarter_final %}
                    {% if forloop.counter <= 2 %}
                    <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                        <div class="match-header">
                            <span class="match-stage">QF-{{ forloop.counter }}</span>
                            <span class="match-status status-{% if match.is_completed %}awarded{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                                {% if match.is_completed %}🏆 获奖
                                {% elif match.battle and match.battle.status == 'running' %}进行中
                                {% else %}待进行
                                {% endif %}
                            </span>
                        </div>
                        <div class="match-players">
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant1.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                            <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant2.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>

        <!-- 左侧4强 -->
        <div class="bracket-side">
            <div class="bracket-round semi-left">
                <div class="round-title">🎉 4强 (左)</div>
                {% for match in matches_by_stage.semi_final %}
                    {% if forloop.counter == 1 %}
                    <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                        <div class="match-header">
                            <span class="match-stage">SF-{{ forloop.counter }}</span>
                            <span class="match-status status-{% if match.is_completed %}awarded{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                                {% if match.is_completed %}🏆 获奖
                                {% elif match.battle and match.battle.status == 'running' %}进行中
                                {% else %}待进行
                                {% endif %}
                            </span>
                        </div>
                        <div class="match-players">
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant1.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                            <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant2.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>

        <!-- 中央区域 -->
        <div class="bracket-center">

            <!-- 决赛 -->
            <div class="bracket-round final">
                <div class="round-title">🎉 决赛</div>
                {% for match in matches_by_stage.final %}
                <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                    <div class="match-header">
                        <span class="match-stage">决赛</span>
                        <span class="match-status status-{% if match.is_completed %}awarded{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                            {% if match.is_completed %}🏆 获奖
                            {% elif match.battle and match.battle.status == 'running' %}进行中
                            {% else %}待进行
                            {% endif %}
                        </span>
                    </div>
                    <div class="match-players">
                        <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                            <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                {{ match.participant1.user.username|default:"待定" }}
                            </span>
                            {% if match.is_completed %}
                            <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                            {% endif %}
                        </div>
                        <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                        <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                            <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                {{ match.participant2.user.username|default:"待定" }}
                            </span>
                            {% if match.is_completed %}
                            <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                            {% endif %}
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- 冠军 -->
            {% if matches_by_stage.final %}
                {% for final_match in matches_by_stage.final %}
                    {% if final_match.is_completed and final_match.winner %}
                    <div class="bracket-round champion">
                        <div class="round-title">👑 冠军</div>
                        <div class="champion-card">
                            <div class="champion-title">🏆 世界杯冠军</div>
                            <div class="champion-name">{{ final_match.winner.user.username }}</div>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
        </div>

        <!-- 右侧4强 -->
        <div class="bracket-side">
            <div class="bracket-round semi-right">
                <div class="round-title">🎉 4强 (右)</div>
                {% for match in matches_by_stage.semi_final %}
                    {% if forloop.counter == 2 %}
                    <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                        <div class="match-header">
                            <span class="match-stage">SF-{{ forloop.counter }}</span>
                            <span class="match-status status-{% if match.is_completed %}awarded{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                                {% if match.is_completed %}🏆 获奖
                                {% elif match.battle and match.battle.status == 'running' %}进行中
                                {% else %}待进行
                                {% endif %}
                            </span>
                        </div>
                        <div class="match-players">
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant1.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                            <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant2.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>

        <!-- 右侧8强 -->
        <div class="bracket-side">
            <div class="bracket-round quarter-right">
                <div class="round-title">🎉 8强 (右)</div>
                {% for match in matches_by_stage.quarter_final %}
                    {% if forloop.counter > 2 %}
                    <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                        <div class="match-header">
                            <span class="match-stage">QF-{{ forloop.counter }}</span>
                            <span class="match-status status-{% if match.is_completed %}awarded{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                                {% if match.is_completed %}🏆 获奖
                                {% elif match.battle and match.battle.status == 'running' %}进行中
                                {% else %}待进行
                                {% endif %}
                            </span>
                        </div>
                        <div class="match-players">
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant1.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                            <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant2.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>

        <!-- 右侧16强 -->
        <div class="bracket-side">
            <div class="bracket-round right-16">
                <div class="round-title">16强 (右)</div>
                {% for match in matches_by_stage.round_16 %}
                    {% if forloop.counter > 4 %}
                    <div class="match-card {% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in-progress{% endif %}{% if match.battle %} clickable{% endif %}" {% if match.battle %}onclick="window.open('{% url 'battles:battle_detail' match.battle.id %}', '_blank')" style="cursor: pointer;"{% endif %}>
                        <div class="match-header">
                            <span class="match-stage">R16-{{ forloop.counter }}</span>
                            <span class="match-status status-{% if match.is_completed %}completed{% elif match.battle and match.battle.status == 'running' %}in_progress{% else %}pending{% endif %}">
                                {% if match.is_completed %}已完成
                                {% elif match.battle and match.battle.status == 'running' %}进行中
                                {% else %}待进行
                                {% endif %}
                            </span>
                        </div>
                        <div class="match-players">
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}loser{% endif %}{% else %}red-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant1 %}winner{% else %}{% endif %}{% else %}red-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant1.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player1_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                            <div class="vs-divider">VS{% if match.is_completed and match.battle %} <i class="fas fa-play-circle replay-icon" title="查看回放" style="margin-left: 8px; color: #ffd700; font-size: 0.9rem;"></i>{% endif %}</div>
                            <div class="player-row {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}loser{% endif %}{% else %}blue-team{% endif %}">
                                <span class="player-name {% if match.is_completed %}{% if match.winner == match.participant2 %}winner{% else %}{% endif %}{% else %}blue-team{% endif %}" style="color: #ffd700;">
                                    {{ match.participant2.user.username|default:"待定" }}
                                </span>
                                {% if match.is_completed %}
                                <span class="player-score" style="color: #ffd700;">{{ match.battle.player2_score|default:"0" }}</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
        </div>
        </div>
    </div>

    <!-- 排行榜内容 -->
    {% if worldcup.status == 'finished' and championship_rankings %}
    <div id="rankings-content" class="tab-content">
        <div class="championship-rankings">
            <div class="rankings-header" style="text-align: center; margin-bottom: 25px; padding: 20px 0; background: rgba(255, 255, 255, 0.1); border-radius: 12px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.2);">
                <h2 style="font-size: 1.8rem; font-weight: bold; margin-bottom: 8px; background: linear-gradient(45deg, #ffd700, #ffed4e); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;">
                    🏆 冠军赛排行榜
                </h2>
                <p style="color: #b0b0b0; font-size: 1rem; margin: 0;">
                    最终排名 - 淘汰赛胜场相同时按常规赛排名排序
                </p>
            </div>

            <div class="rankings-table" style="background: rgba(255, 255, 255, 0.05); border-radius: 12px; overflow: hidden; border: 1px solid rgba(255, 255, 255, 0.1);">
                <div class="table-header" style="display: grid; grid-template-columns: 80px 1fr 120px 120px 150px 120px; gap: 15px; padding: 15px 20px; background: rgba(255, 255, 255, 0.1); font-weight: bold; color: #ffd700; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">
                    <div style="text-align: center;">排名</div>
                    <div>选手</div>
                    <div style="text-align: center;">冠军赛胜场</div>
                    <div style="text-align: center;">常规赛排名</div>
                    <div style="text-align: center;">淘汰阶段</div>
                    <div style="text-align: center;">常规赛积分</div>
                </div>

                {% for ranking in championship_rankings %}
                <div class="ranking-row" style="display: grid; grid-template-columns: 80px 1fr 120px 120px 150px 120px; gap: 15px; padding: 15px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.05); transition: all 0.3s ease; {% if ranking.display_rank <= 3 %}background: rgba(255, 215, 0, 0.1);{% endif %}" onmouseover="this.style.background='rgba(255, 255, 255, 0.1)'" onmouseout="this.style.background='{% if ranking.display_rank <= 3 %}rgba(255, 215, 0, 0.1){% else %}transparent{% endif %}'">
                    <!-- 排名 -->
                    <div style="text-align: center; font-weight: bold; {% if ranking.display_rank == 1 %}color: #ffd700; font-size: 1.2rem;{% elif ranking.display_rank == 2 %}color: #c0c0c0; font-size: 1.1rem;{% elif ranking.display_rank == 3 %}color: #ff8c00; font-size: 1.1rem;{% elif ranking.display_rank == 4 %}color: #ff8c00; font-size: 1rem;{% elif ranking.display_rank >= 5 and ranking.display_rank <= 8 %}color: #d2d451; font-size: 1rem;{% else %}color: #ffffff;{% endif %}">
                        {% if ranking.display_rank == 1 %}
                            🥇 {{ ranking.display_rank }}
                        {% elif ranking.display_rank == 2 %}
                            🥈 {{ ranking.display_rank }}
                        {% elif ranking.display_rank == 3 %}
                            🥉 {{ ranking.display_rank }}
                        {% elif ranking.display_rank >= 4 and ranking.display_rank <= 8 %}
                            🎉 {{ ranking.display_rank }}
                        {% else %}
                            {{ ranking.display_rank }}
                        {% endif %}
                    </div>

                    <!-- 选手名称 -->
                    <div style="font-weight: bold; {% if ranking.display_rank == 1 %}color: #ffd700;{% elif ranking.display_rank == 2 %}color: #c0c0c0;{% elif ranking.display_rank == 3 %}color: #ff8c00;{% elif ranking.display_rank == 4 %}color: #ff8c00;{% elif ranking.display_rank >= 5 and ranking.display_rank <= 8 %}color: #d2d451;{% else %}color: #ffffff;{% endif %}">
                        {{ ranking.participant.user.username }}
                        {% if ranking.display_rank == 1 %}
                            <span style="margin-left: 8px; font-size: 0.8rem; color: #ffd700;">(冠军)👑</span>
                        {% elif ranking.display_rank == 2 %}
                            <span style="margin-left: 8px; font-size: 0.8rem; color: #c0c0c0;">(亚军)</span>
                        {% elif ranking.display_rank == 3 %}
                            <span style="margin-left: 8px; font-size: 0.8rem; color: #ff8c00;">(季军)</span>
                        {% elif ranking.display_rank == 4 %}
                            <span style="margin-left: 8px; font-size: 0.8rem; color: #ff8c00;">(4强)</span>
                        {% elif ranking.display_rank >= 5 and ranking.display_rank <= 8 %}
                            <span style="margin-left: 8px; font-size: 0.8rem; color: #d2d451;">(8强)</span>
                        {% endif %}
                    </div>

                    <!-- 冠军赛胜场 -->
                    <div style="text-align: center; font-weight: bold; color: #28a745;">
                        {{ ranking.championship_wins }}
                    </div>

                    <!-- 常规赛排名 -->
                    <div style="text-align: center; color: #17a2b8;">
                        第{{ ranking.regular_season_rank }}名
                    </div>

                    <!-- 淘汰阶段 -->
                    <div style="text-align: center;">
                        {% if not ranking.eliminated_stage %}
                            <span style="color: #ffd700; font-weight: bold;">🏆 冠军</span>
                        {% elif ranking.eliminated_stage == 'final' %}
                            <span style="color: #c0c0c0;">决赛失败</span>
                        {% elif ranking.eliminated_stage == 'semi_final' %}
                            <span style="color: #cd7f32;">半决赛失败</span>
                        {% elif ranking.eliminated_stage == 'quarter_final' %}
                            <span style="color: #dc3545;">8强失败</span>
                        {% elif ranking.eliminated_stage == 'round_16' %}
                            <span style="color: #6c757d;">16强失败</span>
                        {% else %}
                            <span style="color: #ffc107;">进行中</span>
                        {% endif %}
                    </div>

                    <!-- 常规赛积分 -->
                    <div style="text-align: center; color: #b0b0b0;">
                        {{ ranking.participant.total_score }}
                    </div>
                </div>
                {% endfor %}
            </div>

            <div style="text-align: center; margin-top: 20px; padding: 15px; background: rgba(40, 167, 69, 0.1); border-radius: 8px; border: 1px solid rgba(40, 167, 69, 0.3);">
                <p style="color: #28a745; margin: 0; font-weight: bold;">
                    🎉 冠军赛已结束！恭喜所有参赛选手！
                </p>
            </div>
        </div>
    </div>
    {% endif %}
    {% else %}
    <div class="tournament-bracket">
        <div class="empty-state">
            <div class="empty-icon">🏆</div>
            <h3>冠军赛尚未开始</h3>
            <p>常规赛结束后将自动生成冠军赛对战图</p>
        </div>
    </div>
    {% endif %}

    <!-- 操作按钮 -->
    <div class="action-buttons">
        <a href="{% url 'battles:worldcup_detail' worldcup.id %}" class="btn-action btn-secondary">
            ← 返回详情
        </a>

        {% if worldcup.status == 'regular_season' or worldcup.status == 'finished' %}
        <a href="{% url 'battles:worldcup_regular_season' worldcup.id %}" class="btn-action btn-success">
            🥇 查看常规赛排行榜
        </a>
        {% endif %}
    </div>
</div>

<script>
function switchTab(tabName) {
    // 隐藏所有页签内容
    const allContents = document.querySelectorAll('.tab-content');
    allContents.forEach(content => {
        content.classList.remove('active');
    });

    // 移除所有页签按钮的激活状态
    const allButtons = document.querySelectorAll('.tab-button');
    allButtons.forEach(button => {
        button.classList.remove('active');
    });

    // 显示选中的页签内容
    const targetContent = document.getElementById(tabName + '-content');
    if (targetContent) {
        targetContent.classList.add('active');
    }

    // 激活选中的页签按钮
    const targetButton = document.getElementById(tabName + '-tab');
    if (targetButton) {
        targetButton.classList.add('active');
    }
}

// 自动刷新相关变量
let autoRefreshInterval = null;
let isAutoRefreshActive = false;

// 检查是否应该自动刷新
function shouldAutoRefresh() {
    const worldcupStatus = '{{ worldcup.status }}';
    return worldcupStatus === 'championship';
}

// 自动刷新数据
async function autoRefreshData() {
    if (!shouldAutoRefresh()) {
        stopAutoRefresh();
        return;
    }

    try {
        const worldcupId = {{ worldcup.id }};
        const worldcupStatus = '{{ worldcup.status }}';

        // 首先检查世界杯状态是否发生变化
        const statusResponse = await fetch(`/battles/api/worldcup/${worldcupId}/status/`);
        if (statusResponse.ok) {
            const statusData = await statusResponse.json();
            if (statusData.status === 'success' && statusData.data && statusData.data.status !== worldcupStatus) {
                // 状态发生变化，刷新页面
                console.log(`世界杯状态从 ${worldcupStatus} 变更为 ${statusData.data.status}，刷新页面...`);
                window.location.reload();
                return;
            }
        }

        // 状态未变化，继续正常的数据刷新
        const response = await fetch(`/battles/api/worldcup/${worldcupId}/championship-data/`);

        if (response.ok) {
            const data = await response.json();

            if (data.status === 'success' && data.data) {
                // 更新对战图数据
                if (data.data.championship_matches) {
                    updateBracketData(data.data.championship_matches);
                }

                // 更新排行榜数据
                if (data.data.rankings) {
                    updateRankingsData(data.data.rankings);
                }

                console.log('Championship data refreshed successfully');
            } else {
                console.error('Championship data refresh failed:', data.error || '未知错误');
            }
        } else {
            console.error('Failed to refresh championship data:', response.status);
        }
    } catch (error) {
        console.error('Error refreshing championship data:', error);
    }
}

// 更新对战图数据
function updateBracketData(championshipMatches) {
    // 更新对战图的各个阶段
    const stages = ['round_16', 'quarter_final', 'semi_final', 'final'];

    stages.forEach(stage => {
        if (championshipMatches[stage]) {
            updateStageMatches(stage, championshipMatches[stage]);
        }
    });
}

// 更新阶段比赛数据
function updateStageMatches(stage, matches) {
    matches.forEach((match, index) => {
        // 根据阶段和索引找到对应的比赛卡片
        const matchCards = document.querySelectorAll('.match-card');
        let targetCard = null;

        // 遍历所有比赛卡片，找到匹配的卡片
        matchCards.forEach(card => {
            const stageElement = card.querySelector('.match-stage');
            if (stageElement) {
                const stageText = stageElement.textContent.trim();
                let expectedStageText = '';

                if (stage === 'round_16') {
                    expectedStageText = `R16-${index + 1}`;
                } else if (stage === 'quarter_final') {
                    expectedStageText = `QF-${index + 1}`;
                } else if (stage === 'semi_final') {
                    expectedStageText = `SF-${index + 1}`;
                } else if (stage === 'final') {
                    expectedStageText = 'Final';
                }

                if (stageText === expectedStageText) {
                    targetCard = card;
                }
            }
        });

        if (targetCard && match) {
            updateMatchCard(targetCard, match);
        }
    });
}

// 更新单个比赛卡片
function updateMatchCard(matchCard, matchData) {
    // 更新比赛状态
    const statusElement = matchCard.querySelector('.match-status');
    if (statusElement) {
        const status = matchData.status || (matchData.battle_status === 'finished' ? 'completed' :
                      matchData.battle_status === 'running' ? 'in_progress' : 'pending');
        statusElement.textContent = getMatchStatusText(status);
        statusElement.className = `match-status status-${status}`;
    }

    // 更新比赛卡片的状态类
    matchCard.className = matchCard.className.replace(/\b(completed|in-progress)\b/g, '');
    if (matchData.status === 'completed' || matchData.battle_status === 'finished') {
        matchCard.classList.add('completed');
    } else if (matchData.battle_status === 'running') {
        matchCard.classList.add('in-progress');
    }

    // 更新选手信息
    const playerRows = matchCard.querySelectorAll('.player-row');
    if (playerRows.length >= 2) {
        // 更新第一个选手
        updatePlayerRow(playerRows[0], matchData.player1, matchData.winner === matchData.player1, matchData, true);

        // 更新第二个选手
        updatePlayerRow(playerRows[1], matchData.player2, matchData.winner === matchData.player2, matchData, false);
    }

    // 如果有战斗ID，添加点击事件
    if (matchData.battle_id) {
        matchCard.style.cursor = 'pointer';
        matchCard.onclick = function() {
            window.open(`/battles/${matchData.battle_id}/`, '_blank');
        };
    }
}

// 更新选手行信息
function updatePlayerRow(playerRow, playerName, isWinner, matchData, isFirstPlayer = true) {
    const nameElement = playerRow.querySelector('.player-name');
    const scoreElement = playerRow.querySelector('.player-score');

    if (nameElement && playerName) {
        nameElement.textContent = playerName;

        // 更新胜负状态样式
        if (matchData.status === 'completed' || matchData.battle_status === 'finished') {
            if (isWinner) {
                nameElement.classList.add('winner');
                playerRow.classList.add('winner');
                playerRow.classList.remove('loser', 'red-team', 'blue-team');
            } else {
                nameElement.classList.remove('winner');
                playerRow.classList.add('loser');
                playerRow.classList.remove('winner');
                // 非胜利方根据位置添加红蓝样式
                if (isFirstPlayer) {
                    playerRow.classList.add('red-team');
                    playerRow.classList.remove('blue-team');
                    nameElement.classList.add('red-team');
                    nameElement.classList.remove('blue-team');
                } else {
                    playerRow.classList.add('blue-team');
                    playerRow.classList.remove('red-team');
                    nameElement.classList.add('blue-team');
                    nameElement.classList.remove('red-team');
                }
            }
        } else {
            // 对于进行中或待进行的比赛，根据位置添加红蓝样式
            nameElement.classList.remove('winner');
            playerRow.classList.remove('winner', 'loser');

            if (isFirstPlayer) {
                playerRow.classList.add('red-team');
                playerRow.classList.remove('blue-team');
                nameElement.classList.add('red-team');
                nameElement.classList.remove('blue-team');
            } else {
                playerRow.classList.add('blue-team');
                playerRow.classList.remove('red-team');
                nameElement.classList.add('blue-team');
                nameElement.classList.remove('red-team');
            }
        }
    }

    // 更新分数（如果比赛已完成且有战斗结果）
    if (scoreElement && (matchData.status === 'completed' || matchData.battle_status === 'finished')) {
        // 这里需要根据实际的API数据结构来获取分数
        // 暂时显示默认分数，实际应该从battle结果中获取
        if (isWinner) {
            scoreElement.textContent = '1';
        } else {
            scoreElement.textContent = '0';
        }
        scoreElement.style.display = 'block';
    } else if (scoreElement) {
        scoreElement.style.display = 'none';
    }
}

// 获取比赛状态文本
function getMatchStatusText(status) {
    const statusMap = {
        'pending': '待开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'awarded': '🏆 获奖',
        'running': '进行中',
        'finished': '🏆 获奖'
    };
    return statusMap[status] || status;
}

// 更新排行榜数据
function updateRankingsData(rankings) {
    const rankingsContainer = document.querySelector('.championship-rankings .rankings-list');
    if (!rankingsContainer) return;

    // 清空现有排行榜
    rankingsContainer.innerHTML = '';

    // 重新生成排行榜
    rankings.forEach((ranking, index) => {
        const rankingElement = createRankingElement(ranking, index + 1);
        rankingsContainer.appendChild(rankingElement);
    });
}

// 创建排行榜元素
function createRankingElement(ranking, position) {
    const div = document.createElement('div');
    div.className = 'ranking-row';

    div.innerHTML = `
        <div style="text-align: center; font-weight: bold; color: ${getRankColor(position)};">
            ${position}
        </div>
        <div style="display: flex; align-items: center; gap: 8px;">
            <img src="${ranking.participant.avatar_url || '/static/images/default_avatar.png'}"
                 alt="${ranking.participant.name}"
                 style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover;">
            <span style="font-weight: bold;">${ranking.participant.name}</span>
        </div>
        <div style="text-align: center; font-weight: bold; color: #28a745;">
            ${ranking.championship_wins}
        </div>
        <div style="text-align: center; color: #17a2b8;">
            第${ranking.regular_season_rank}名
        </div>
        <div style="text-align: center;">
            ${getEliminationStageText(ranking.eliminated_stage)}
        </div>
        <div style="text-align: center; color: #b0b0b0;">
            ${ranking.participant.total_score}
        </div>
    `;

    return div;
}

// 获取排名颜色
function getRankColor(position) {
    if (position === 1) return '#ffd700';
    if (position === 2) return '#c0c0c0';
    if (position === 3) return '#cd7f32';
    return '#ffffff';
}

// 获取淘汰阶段文本
function getEliminationStageText(stage) {
    if (!stage) return '<span style="color: #ffd700; font-weight: bold;">🏆 冠军</span>';

    const stageMap = {
        'final': '<span style="color: #c0c0c0;">决赛失败</span>',
        'semi_final': '<span style="color: #cd7f32;">半决赛失败</span>',
        'quarter_final': '<span style="color: #dc3545;">8强失败</span>',
        'round_16': '<span style="color: #6c757d;">16强失败</span>'
    };

    return stageMap[stage] || '<span style="color: #ffc107;">进行中</span>';
}

// 开始自动刷新
function startAutoRefresh() {
    if (!shouldAutoRefresh() || isAutoRefreshActive) {
        return;
    }

    isAutoRefreshActive = true;
    addAutoRefreshIndicator();

    // 立即刷新一次
    autoRefreshData();

    // 设置定时刷新（每10秒）
    autoRefreshInterval = setInterval(autoRefreshData, 10000);

    console.log('Auto refresh started for championship page');
}

// 停止自动刷新
function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
    }

    isAutoRefreshActive = false;
    removeAutoRefreshIndicator();

    console.log('Auto refresh stopped for championship page');
}

// 添加自动刷新指示器
function addAutoRefreshIndicator() {
    // 避免重复添加
    if (document.querySelector('.auto-refresh-indicator')) {
        return;
    }

    const indicator = document.createElement('div');
    indicator.className = 'auto-refresh-indicator';
    indicator.innerHTML = `
        <div style="position: fixed; top: 20px; right: 20px; z-index: 1000;
                    background: rgba(40, 167, 69, 0.9); color: white;
                    padding: 8px 16px; border-radius: 20px; font-size: 12px;
                    display: flex; align-items: center; gap: 8px;
                    backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.2);">
            <div style="width: 8px; height: 8px; background: #fff; border-radius: 50%;
                        animation: pulse 1.5s infinite;"></div>
            自动刷新中
        </div>
        <style>
            @keyframes pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.3; }
            }
        </style>
    `;

    document.body.appendChild(indicator);
}

// 移除自动刷新指示器
function removeAutoRefreshIndicator() {
    const indicator = document.querySelector('.auto-refresh-indicator');
    if (indicator) {
        indicator.remove();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 默认显示对战图页签
    switchTab('bracket');

    // 启动自动刷新
    if (shouldAutoRefresh()) {
        startAutoRefresh();
    }
});

// 页面可见性变化时的处理
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面隐藏时停止自动刷新
        stopAutoRefresh();
    } else {
        // 页面显示时重新开始自动刷新
        if (shouldAutoRefresh()) {
            startAutoRefresh();
        }
    }
});

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});
</script>
{% endblock %}
